package com.xbongbong.pro.message.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.message.domain.entity.PushSetEntity;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.IdNamePropertyPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.Entity;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.message.constant.MessageSetDetailTitleConstants;
import com.xbongbong.pro.message.enums.PushObjectTypeEnum;
import com.xbongbong.pro.message.enums.PushParentTypeEnum;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.pojo.MessageSetDetailPojo;
import com.xbongbong.pro.message.pojo.dto.MessageSetDetailDTO;
import com.xbongbong.pro.message.pojo.vo.MessageSetDetailVO;
import com.xbongbong.pro.message.pojo.vo.PushSetVO;
import com.xbongbong.pro.message.pushset.CommunicatePlanPushSet;
import com.xbongbong.pro.message.pushset.CommunicatePushSet;
import com.xbongbong.pro.message.pushset.ContractPushSet;
import com.xbongbong.pro.message.pushset.ContractRemindPushSet;
import com.xbongbong.pro.message.pushset.CustomerAttrPushSet;
import com.xbongbong.pro.message.pushset.CustomerContactPushSet;
import com.xbongbong.pro.message.pushset.CustomerPushSet;
import com.xbongbong.pro.message.pushset.OpportunityPushSet;
import com.xbongbong.pro.message.pushset.QuotationPushSet;
import com.xbongbong.pro.message.pushset.QuotationRemindPushSet;
import com.xbongbong.pro.message.pushset.SalePushSet;
import com.xbongbong.pro.message.pushset.SignInPushSet;
import com.xbongbong.pro.message.pushset.WorkReportOverduePushSet;
import com.xbongbong.pro.message.pushset.WorkReportPushSet;
import com.xbongbong.pro.message.pushset.WorkReportRemindPushSet;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.SignInEntity;
import com.xbongbong.saas.domain.entity.WorkReportCcEntity;
import com.xbongbong.saas.domain.entity.WorkReportSetEntity;
import com.xbongbong.saas.domain.entity.ext.ContactEntityExt;
import com.xbongbong.saas.domain.entity.ext.ContractEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerCommunicateEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.domain.entity.ext.OpportunityEntityExt;
import com.xbongbong.saas.domain.entity.ext.QuotationEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkReportEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.WorkReportFieldEnum;
import com.xbongbong.saas.model.ContractUserModel;
import com.xbongbong.saas.model.CustomerUserModel;
import com.xbongbong.saas.model.OpportunityUserModel;
import com.xbongbong.saas.model.QuotationUserModel;
import com.xbongbong.saas.model.WorkReportCcModel;
import com.xbongbong.saas.model.WorkReportSetModel;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserDepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserDepartmentModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * CRM消息设置服务实现类
 *
 * @author LiZhikang
 * @date 2022/11/4 16:59
 */
@Service
@Slf4j
public class CrmMessageSetServiceImpl extends AbstractMessageSetService {

    @Resource
    private CommonHelp commonHelp;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;

    @Resource
    private CustomerUserModel customerUserModel;
    @Resource
    private OpportunityUserModel opportunityUserModel;
    @Resource
    private ContractUserModel contractUserModel;
    @Resource
    private WorkReportCcModel workReportCcModel;
    @Resource
    private QuotationUserModel quotationUserModel;
    @Resource
    private WorkReportSetModel workReportSetModel;


    @Override
    public List<String> alias() {
        return Collections.singletonList(XbbRefTypeEnum.CRM.getAlias());
    }

    @Override
    public String initSetDetailList() throws Exception {
        return null;
    }

    @Override
    public MessageSetDetailVO getSetDetailList(MessageSetDetailDTO messageSetDetailDTO) throws Exception {
        List<MessageSetDetailPojo> messageSetDetailPojos = new ArrayList<>();
        Integer typeInt = messageSetDetailDTO.getSaasIds().get(0).intValue();
        typeInt = XbbRefTypeEnum.transferBusinessType4Distributor(typeInt, messageSetDetailDTO.getDistributorMark());
        String alias = PushTypeEnum.getByCode(typeInt).getAlias();
        if (!Objects.equals(alias, PushTypeEnum.UNKNOWN.getAlias())) {
            String methodName = "getMessageSetSaas" + alias.substring(0, 1).toUpperCase() + alias.substring(1) + "DetailList";
            Method method = this.getClass().getDeclaredMethod(methodName, String.class, List.class, Integer.class);
            method.invoke(this, messageSetDetailDTO.getCorpid(), messageSetDetailPojos, typeInt);
        }
        return new MessageSetDetailVO(messageSetDetailPojos);
    }

    /**
     * 客户 100
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasCustomerPushDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> pushTypeEnumList = new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt));
        List<PushTypeEnum> baseTypeEnum = new ArrayList<>();
        List<PushTypeEnum> otherTypeEnum = new ArrayList<>();
        boolean isCustomerPublicSeniorModel = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
        for (PushTypeEnum pushTypeEnum : pushTypeEnumList) {
            Integer subCode = pushTypeEnum.getSubCode();
            boolean transferPush = isCustomerPublicSeniorModel && Objects.equals(subCode, PushTypeEnum.CUSTOMER_TRANSFER_PUBLIC.getSubCode());
            if (Objects.equals(subCode, PushTypeEnum.CUSTOMER_ADD_PUSH.getSubCode())
                    || Objects.equals(subCode, PushTypeEnum.CUSTOMER_CHANGE_PUSH.getSubCode()) || Objects.equals(subCode, PushTypeEnum.CUSTOMER_BACK_PUBLIC.getSubCode()) || transferPush) {
                baseTypeEnum.add(pushTypeEnum);
            }
            if (Objects.equals(subCode, PushTypeEnum.CUSTOMER_HANDOVER_PUSH.getSubCode()) || Objects.equals(subCode, PushTypeEnum.CUSTOMER_DISTRIBUTION_PUSH.getSubCode()) || Objects.equals(subCode, PushTypeEnum.CUSTOMER_TEAM_ADD_DEL_MAIN.getSubCode()) || Objects.equals(subCode, PushTypeEnum.CUSTOMER_TEAM_ADD_DEL_SYNERGETIC.getSubCode())) {
                otherTypeEnum.add(pushTypeEnum);
            }
        }

        CustomerPushSet customerPushSet = new CustomerPushSet();
        MessageSetDetailPojo baseDetail = new MessageSetDetailPojo();
        baseDetail.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.CUSTOMER_BASE));

        List<PushSetEntity> basePushTypeList = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : baseTypeEnum) {
            PushSetEntity pushSetEntity = customerPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            basePushTypeList.add(pushSetEntity);
        }
        List<PushSetVO> basePushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(basePushTypeList, basePushSetVOList, PushSetVO.class);
        baseDetail.setValue(basePushSetVOList);

        messageSetDetailPojos.add(baseDetail);

        MessageSetDetailPojo otherDetail = new MessageSetDetailPojo();
        otherDetail.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.CUSTOMER_FOLLOW));
        List<PushSetEntity> otherPushTypeList = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : otherTypeEnum) {
            PushSetEntity pushSetEntity = customerPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            otherPushTypeList.add(pushSetEntity);
        }
        List<PushSetVO> otherPushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(otherPushTypeList, otherPushSetVOList, PushSetVO.class);
        otherDetail.setValue(otherPushSetVOList);

        messageSetDetailPojos.add(otherDetail);
    }

    /**
     * 客户自定义提醒 111
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws XbbException
     */
    private void getMessageSetSaasCustomerRemindDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws InstantiationException, IllegalAccessException, XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("enable", 1);
        param.put("businessType", XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        param.put("saasMark", SaasMarkEnum.SAAS.getCode());
        List<PaasFormEntityExt> paasFormEntityExtList = paasFormModel.list(param);
        List<Long> formIds = new ArrayList<>();
        for (PaasFormEntityExt entityExt : paasFormEntityExtList) {
            formIds.add(entityExt.getId());
        }
        param.clear();
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("formIdIn", formIds);
        List<PaasFormExplainEntity> paasFormExplainEntityExtList = paasFormExplainModel.findEntitys(param);
        Map<Long, Map<String, FieldAttrEntity>> formIdAndExplainMap = new HashMap<>();
        for (PaasFormExplainEntity explainEntityExt : paasFormExplainEntityExtList) {
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explainEntityExt.getExplains());
            formIdAndExplainMap.put(explainEntityExt.getFormId(), explainMap);
        }
        CustomerAttrPushSet customerAttrPushSet = new CustomerAttrPushSet();
        for (PaasFormEntityExt entity : paasFormEntityExtList) {
            Long formId = entity.getId();
            List<PushSetEntity> pushSetEntityList = new ArrayList<>();
            Map<String, FieldAttrEntity> fieldAttrEntityMap = formIdAndExplainMap.get(formId);
            List<String> attrList = new ArrayList<>();
            if (Objects.nonNull(fieldAttrEntityMap)) {
                for (Map.Entry<String, FieldAttrEntity> entry : fieldAttrEntityMap.entrySet()) {
                    String key = entry.getKey();
                    FieldAttrEntity fieldAttrEntity = entry.getValue();
                    if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.DATETIME.getType()) && Objects.equals(fieldAttrEntity.getIsRedundant(), 1)) {
                        attrList.add(key);
                    }
                }
            }

            pushSetEntityList = customerAttrPushSet.getPushSet(corpid, attrList, pushSetModel, formId);
            pushSetEntityList.forEach(v -> {
                FieldAttrEntity fieldAttrEntity = fieldAttrEntityMap.get(v.getAttrEntity());
                v.setTitle(fieldAttrEntity.getAttrName());
            });

            List<PushSetVO> pushSetVOList = new ArrayList<>();
            BeanUtil.copyPropertiesList(pushSetEntityList, pushSetVOList, PushSetVO.class);

            MessageSetDetailPojo messageSetDetailPojo = new MessageSetDetailPojo();
            messageSetDetailPojo.setTitle(entity.getName());
            messageSetDetailPojo.setValue(pushSetVOList);
            messageSetDetailPojos.add(messageSetDetailPojo);
        }
    }

    /**
     * 合同 201
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasContractPushDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> pushTypeEnumList = new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt));
        List<PushTypeEnum> basePushTypeEnum = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : pushTypeEnumList) {
            if (Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.CONTRACT_ADD_PUSH.getSubCode()) || Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.CONTRACT_CHANGE_PUSH.getSubCode()) || Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.CONTRACT_TEAM_ADD_DEL_MAIN_PUSH.getSubCode()) || Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.CONTRACT_TEAM_ADD_DEL_SYNERGETIC_PUSH.getSubCode())) {
                basePushTypeEnum.add(pushTypeEnum);
            }
        }

        ContractPushSet contractPushSet = new ContractPushSet();
        MessageSetDetailPojo detailPojo = new MessageSetDetailPojo();
        detailPojo.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.CONTRACT_BASE));
        List<PushSetEntity> basePushTypeList = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : basePushTypeEnum) {
            PushSetEntity pushSetEntity = contractPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            basePushTypeList.add(pushSetEntity);
        }
        List<PushSetVO> pushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(basePushTypeList, pushSetVOList, PushSetVO.class);
        detailPojo.setValue(pushSetVOList);
        messageSetDetailPojos.add(detailPojo);
        //201调203继续执行
        this.getMessageSetSaasContractRemindDetailList(corpid, messageSetDetailPojos, XbbRefTypeEnum.CONTRACT_REMIND.getCode());
    }

    /**
     * 合同到期提醒 203
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasContractRemindDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> pushTypeEnumList = new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt));
        ContractRemindPushSet contractRemindPushSet = new ContractRemindPushSet();
        MessageSetDetailPojo detailPojo = new MessageSetDetailPojo();
        detailPojo.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.CONTRACT_REMIND));
        List<PushSetEntity> basePushTypeList = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : pushTypeEnumList) {
            PushSetEntity pushSetEntity = contractRemindPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            basePushTypeList.add(pushSetEntity);
        }
        List<PushSetVO> pushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(basePushTypeList, pushSetVOList, PushSetVO.class);
        detailPojo.setValue(pushSetVOList);
        messageSetDetailPojos.add(detailPojo);
    }

    /**
     * 销售机会 301
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasOpportunityPushDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> pushTypeEnumList = new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt));
        List<PushTypeEnum> basePushTypeEnum = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : pushTypeEnumList) {
            if (pushTypeEnum.getSubCode() > 0) {
                basePushTypeEnum.add(pushTypeEnum);
            }
        }

        OpportunityPushSet opportunityPushSet = new OpportunityPushSet();
        MessageSetDetailPojo baseDetail = new MessageSetDetailPojo();
        baseDetail.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.OPPORTUNITY_BASE));
        List<PushSetEntity> basePushTypeList = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : basePushTypeEnum) {
            PushSetEntity pushSetEntity = opportunityPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            basePushTypeList.add(pushSetEntity);
        }
        List<PushSetVO> pushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(basePushTypeList, pushSetVOList, PushSetVO.class);
        baseDetail.setValue(pushSetVOList);

        messageSetDetailPojos.add(baseDetail);
    }

    /**
     * 联系人 401
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasContactPushDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> pushTypeEnumList = new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt));

        List<PushTypeEnum> basePusTypeEnum = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : pushTypeEnumList) {
            if (Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.CONTACT_NEW.getSubCode())) {
                basePusTypeEnum.add(pushTypeEnum);
            }
        }
        CustomerContactPushSet customerContactPushSet = new CustomerContactPushSet();
        MessageSetDetailPojo baseDetail = new MessageSetDetailPojo();
        baseDetail.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.CONTACT_BASE));

        List<PushSetEntity> basePushTypeList = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : basePusTypeEnum) {
            PushSetEntity pushSetEntity = customerContactPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            basePushTypeList.add(pushSetEntity);
        }
        List<PushSetVO> pushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(basePushTypeList, pushSetVOList, PushSetVO.class);
        baseDetail.setValue(pushSetVOList);

        messageSetDetailPojos.add(baseDetail);
    }

    /**
     * 跟进记录 501
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasCommunicatePushDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> pushTypeEnumList = new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt));
        List<PushTypeEnum> basePushTypeEnum = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : pushTypeEnumList) {
            if (Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.COMMUNICATE_ADD_PUSH.getSubCode())) {
                basePushTypeEnum.add(pushTypeEnum);
            }
        }

        CommunicatePushSet communicatePushSet = new CommunicatePushSet();
        MessageSetDetailPojo detailPojo = new MessageSetDetailPojo();
        detailPojo.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.COMMUNICATE_BASE));
        List<PushSetEntity> basePushTypeList = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : basePushTypeEnum) {
            PushSetEntity pushSetEntity = communicatePushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            basePushTypeList.add(pushSetEntity);
        }
        List<PushSetVO> pushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(basePushTypeList, pushSetVOList, PushSetVO.class);
        detailPojo.setValue(pushSetVOList);
        messageSetDetailPojos.add(detailPojo);
    }

    /**
     * 访客计划 601
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasCommunicatePlanPushDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> pushTypeEnumList = new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt));
        List<PushTypeEnum> basePushTypeEnum = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : pushTypeEnumList) {
            if (Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.COMMUNICATE_PLAN_ADD_PUSH.getSubCode())) {
                basePushTypeEnum.add(pushTypeEnum);
            }
        }

        CommunicatePlanPushSet communicatePlanPushSet = new CommunicatePlanPushSet();
        MessageSetDetailPojo detailPojo = new MessageSetDetailPojo();
        detailPojo.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.COMMUNICATE_PLAN_BASE));
        List<PushSetEntity> basePushTypeList = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : basePushTypeEnum) {
            PushSetEntity pushSetEntity = communicatePlanPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            basePushTypeList.add(pushSetEntity);
        }
        List<PushSetVO> pushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(basePushTypeList, pushSetVOList, PushSetVO.class);
        detailPojo.setValue(pushSetVOList);
        messageSetDetailPojos.add(detailPojo);
    }

    /**
     * 签到 2001
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasSignInAddPushDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> pushTypeEnumList = new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt));

        SignInPushSet signInPushSet = new SignInPushSet();
        List<PushSetEntity> basePushSetList = new ArrayList<>();
        MessageSetDetailPojo detailPojo = new MessageSetDetailPojo();
        detailPojo.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.SIGN_IN_BASE));
        for (PushTypeEnum pushTypeEnum : pushTypeEnumList) {
            PushSetEntity pushSetEntity = signInPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            basePushSetList.add(pushSetEntity);
        }
        List<PushSetVO> pushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(basePushSetList, pushSetVOList, PushSetVO.class);
        detailPojo.setValue(pushSetVOList);
        messageSetDetailPojos.add(detailPojo);
    }

    /**
     * 工作报告 2101
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasWorkReportPushDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> pushTypeEnumList = new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt));
        List<PushTypeEnum> basePushTypeEnum = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : pushTypeEnumList) {
            if (Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.WORK_REPORT_ADD_PUSH.getSubCode()) || Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.WORK_REPORT_REMIND_PUSH.getSubCode()) || Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.WORK_REPORT_OVERDUE_PUSH.getSubCode())) {
                basePushTypeEnum.add(pushTypeEnum);
            }
        }

        WorkReportPushSet workReportPushSet = new WorkReportPushSet();
        WorkReportRemindPushSet workReportRemindPushSet = new WorkReportRemindPushSet();
        WorkReportOverduePushSet workReportOverduePushSet = new WorkReportOverduePushSet();
        MessageSetDetailPojo detailPojo = new MessageSetDetailPojo();
        detailPojo.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.WORK_REPORT_BASE));
        List<PushSetEntity> basePushSetList = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : basePushTypeEnum) {
            if (Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.WORK_REPORT_ADD_PUSH.getSubCode())) {
                PushSetEntity pushSetEntity = workReportPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
                basePushSetList.add(pushSetEntity);
            } else if (Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.WORK_REPORT_REMIND_PUSH.getSubCode())) {
                PushSetEntity pushSetEntity = workReportRemindPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
                basePushSetList.add(pushSetEntity);
            } else if (Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.WORK_REPORT_OVERDUE_PUSH.getSubCode())) {
                PushSetEntity pushSetEntity = workReportOverduePushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
                basePushSetList.add(pushSetEntity);
            }
        }
        List<PushSetVO> pushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(basePushSetList, pushSetVOList, PushSetVO.class);
        detailPojo.setValue(pushSetVOList);
        messageSetDetailPojos.add(detailPojo);
    }

    /**
     * 销售简报 2301
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasSaleReportPushDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> pushTypeEnumList = new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt));
        SalePushSet salePushSet = new SalePushSet();
        List<PushSetEntity> basePushSetList = new ArrayList<>();
        MessageSetDetailPojo detailPojo = new MessageSetDetailPojo();
        detailPojo.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.SALE_REPORT_BASE));
        for (PushTypeEnum pushTypeEnum : pushTypeEnumList) {
            PushSetEntity pushSetEntity = salePushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            basePushSetList.add(pushSetEntity);
        }
        List<PushSetVO> pushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(basePushSetList, pushSetVOList, PushSetVO.class);
        detailPojo.setValue(pushSetVOList);
        messageSetDetailPojos.add(detailPojo);
    }

    /**
     * 报价单 4700
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasQuotationPushDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> pushTypeEnumList = new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt));
        List<PushTypeEnum> basePushTypeEnum = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : pushTypeEnumList) {
            if (Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.QUOTATION_ADD_PUSH.getSubCode()) || Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.QUOTATION_STATUS_PUSH.getSubCode()) || Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.QUOTATION_TEAM_ADD_DEL_MAIN_PUSH.getSubCode()) || Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.QUOTATION_TEAM_ADD_DEL_SYNERGETIC_PUSH.getSubCode())) {
                basePushTypeEnum.add(pushTypeEnum);
            }
        }

        QuotationPushSet quotationPushSet = new QuotationPushSet();
        MessageSetDetailPojo detailPojo = new MessageSetDetailPojo();
        detailPojo.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.QUOTATION_RASE));
        List<PushSetEntity> basePushTypeList = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : basePushTypeEnum) {
            PushSetEntity pushSetEntity = quotationPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            basePushTypeList.add(pushSetEntity);
        }
        List<PushSetVO> pushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(basePushTypeList, pushSetVOList, PushSetVO.class);
        detailPojo.setValue(pushSetVOList);
        messageSetDetailPojos.add(detailPojo);
        //4701调4703
        this.getMessageSetSaasQuotationRemindDetailList(corpid, messageSetDetailPojos, XbbRefTypeEnum.QUOTATION_REMIND.getCode());
    }

    /**
     * 报价单到期提醒 4703
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasQuotationRemindDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> pushTypeEnumList = new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt));
        QuotationRemindPushSet quotationRemindPushSet = new QuotationRemindPushSet();
        MessageSetDetailPojo detailPojo = new MessageSetDetailPojo();
        detailPojo.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.QUOTATION_REMIND));
        List<PushSetEntity> basePushTypeList = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : pushTypeEnumList) {
            PushSetEntity pushSetEntity = quotationRemindPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            basePushTypeList.add(pushSetEntity);
        }
        List<PushSetVO> pushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(basePushTypeList, pushSetVOList, PushSetVO.class);
        detailPojo.setValue(pushSetVOList);
        messageSetDetailPojos.add(detailPojo);
    }


    @Override
    public List<String> getUserIdListByPushSetRule(String corpid, Integer type, Integer subType, UserEntity userEntity, Entity entity) throws Exception {
        String alias = PushParentTypeEnum.getByCode(type).getAlias();
        String methodName = "get" + alias.substring(0, 1).toUpperCase() + alias.substring(1) + "UserIdList";
        Method method = this.getClass().getDeclaredMethod(methodName, String.class, Integer.class, UserEntity.class, Entity.class);
        Object userIds = method.invoke(this, corpid, subType, userEntity, entity);
        return distinct(userIds);
    }

    /**
     * 客户 100
     *
     * @param corpid
     * @param subType
     * @param userEntity
     * @param entity
     * @return
     */
    private List<String> getCustomerManagementUserIdList(String corpid, Integer subType, UserEntity userEntity, Entity entity) {
        String pushObjectString;
        Set<String> userIdList = new HashSet<>();
        CustomerEntityExt customerEntity = (CustomerEntityExt) entity;
        Long customerId = customerEntity.getId();
        CustomerPushSet customerPushSet = new CustomerPushSet();
        PushSetEntity pushSetEntity = customerPushSet.getPushSet(corpid, subType, pushSetModel);

        if (Objects.equals(pushSetEntity.getEnable(), 1)) {
            pushObjectString = pushSetEntity.getPushObject();
            JSONObject pushObject = JsonHelperUtil.parseObject(pushObjectString);
            String typeString = pushObject.getString("type");
            if (customerId != null && customerId > 0) {
                JSONArray typeJsonArray = JsonHelperUtil.parseArray(typeString);
                for (Object object : typeJsonArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    Integer enable = jsonObject.getInteger("enable");
                    if (Objects.equals(enable, 1)) {
                        String alias = jsonObject.getString("alias");
                        if (Objects.equals(alias, PushObjectTypeEnum.MAINUSER.getAlias())) {
                            userIdList.addAll(customerUserModel.getCustomerUserIdList(corpid, Collections.singletonList(customerId), 1));
                        }
                        if (Objects.equals(alias, PushObjectTypeEnum.COLLABORATOR.getAlias())) {
                            userIdList.addAll(customerUserModel.getCustomerUserIdList(corpid, Collections.singletonList(customerId), 0));
                        }
                    }
                }
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(userIdList), DateUtil.getInt());
            } else {
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(userIdList), DateUtil.getInt());
            }
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 客户自定义提醒 111
     *
     * @param corpid
     * @param subType
     * @param userEntity
     * @param entity
     * @return
     */
    private List<String> getCustomerRemindUserIdList(String corpid, Integer subType, UserEntity userEntity, Entity entity) {
        //客户自定义模块的推送走轮询，不在这里处理
        return new ArrayList<>();
    }

    /**
     * 合同 201
     *
     * @param corpid
     * @param subType
     * @param userEntity
     * @param entity
     * @return
     */
    private List<String> getContractUserIdList(String corpid, Integer subType, UserEntity userEntity, Entity entity) {
        String pushObjectString;
        Set<String> result = new HashSet<>();
        ContractEntityExt contractEntity = (ContractEntityExt) entity;
        ContractPushSet contractPushSet = new ContractPushSet();
        PushSetEntity pushSetEntity = contractPushSet.getPushSet(corpid, subType, pushSetModel);
        Long contractId = contractEntity.getId();

        if (Objects.equals(pushSetEntity.getEnable(), 1)) {
            pushObjectString = pushSetEntity.getPushObject();
            JSONObject pushObject = JsonHelperUtil.parseObject(pushObjectString);
            String typeString = pushObject.getString("type");
            if (contractId != null && contractId > 0) {
                JSONArray typeJsonArray = JsonHelperUtil.parseArray(typeString);
                for (Object object : typeJsonArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    Integer enable = jsonObject.getInteger("enable");
                    if (Objects.equals(enable, 1)) {
                        String alias = jsonObject.getString("alias");
                        if (Objects.equals(alias, PushObjectTypeEnum.MAINUSER.getAlias())) {
                            result.addAll(contractUserModel.getContractUserIdList(corpid, contractEntity.getId(), 1));
                        }
                        if (Objects.equals(alias, PushObjectTypeEnum.COLLABORATOR.getAlias())) {
                            result.addAll(contractUserModel.getContractUserIdList(corpid, contractEntity.getId(), 0));
                        }
                        if (Objects.equals(alias, PushObjectTypeEnum.CONTRACT_SIGNING.getAlias())) {
                            JSONObject contractDataObject = JsonHelperUtil.getJSONObject(contractEntity.getData());
                            result.add(contractDataObject.getString(ContractEnum.SIGN_PERSON.getAttr()));
                        }
                    }
                }
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
            } else {
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
            }
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 销售机会 301
     *
     * @param corpid
     * @param subType
     * @param userEntity
     * @param entity
     * @return
     */
    private List<String> getSalesOpportunityUserIdList(String corpid, Integer subType, UserEntity userEntity, Entity entity) {
        String pushObjectString;
        Set<String> result = new HashSet<>();
        OpportunityEntityExt opportunityEntity = (OpportunityEntityExt) entity;
        Long opportunityId = opportunityEntity.getId();
        OpportunityPushSet opportunityPushSet = new OpportunityPushSet();
        PushSetEntity pushSetEntity = opportunityPushSet.getPushSet(corpid, subType, pushSetModel);

        if (Objects.equals(pushSetEntity.getEnable(), 1)) {
            pushObjectString = pushSetEntity.getPushObject();
            JSONObject pushObject = JsonHelperUtil.parseObject(pushObjectString);
            String typeString = pushObject.getString("type");
            if (opportunityId != null && opportunityId > 0) {
                JSONArray typeJsonArray = JsonHelperUtil.parseArray(typeString);
                for (Object object : typeJsonArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    Integer enable = jsonObject.getInteger("enable");
                    if (Objects.equals(enable, 1)) {
                        String alias = jsonObject.getString("alias");
                        if (Objects.equals(alias, PushObjectTypeEnum.MAINUSER.getAlias())) {
                            result.addAll(opportunityUserModel.getOpportunityUserIdList(corpid, opportunityId, 1));
                        }
                        if (Objects.equals(alias, PushObjectTypeEnum.COLLABORATOR.getAlias())) {
                            result.addAll(opportunityUserModel.getOpportunityUserIdList(corpid, opportunityId, 0));
                        }
                    }
                }
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
            } else {
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
            }
        } else {
            return new ArrayList<>();
        }
    }


    /**
     * 联系人 401
     *
     * @param corpid
     * @param subType
     * @param userEntity
     * @param entity
     * @return
     */
    private List<String> getContactUserIdList(String corpid, Integer subType, UserEntity userEntity, Entity entity) {
        String pushObjectString;
        Set<String> result = new HashSet<>();
        ContactEntityExt contactEntity = (ContactEntityExt) entity;

        JSONObject dataObject = JsonHelperUtil.getJSONObject(contactEntity.getData());
        Long customerId = dataObject.getLong(ContactEnum.CUSTOMER_NAME.getAttr());
        CustomerContactPushSet customerContactPushSet = new CustomerContactPushSet();
        PushSetEntity pushSetEntity = customerContactPushSet.getPushSet(corpid, subType, pushSetModel);

        if (Objects.equals(pushSetEntity.getEnable(), 1)) {
            //只有新数据
            pushObjectString = pushSetEntity.getPushObject();
            JSONObject pushObject = JsonHelperUtil.parseObject(pushObjectString);
            String typeString = pushObject.getString("type");

            if (customerId != null && customerId > 0) {
                JSONArray typeJsonArray = JsonHelperUtil.parseArray(typeString);
                for (Object object : typeJsonArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    Integer enable = jsonObject.getInteger("enable");
                    if (Objects.equals(enable, 1)) {
                        String alias = jsonObject.getString("alias");
                        if (Objects.equals(alias, PushObjectTypeEnum.MAINUSER.getAlias())) {
                            result.addAll(customerUserModel.getCustomerUserIdList(corpid, Collections.singletonList(customerId), 1));
                        }
                        if (Objects.equals(alias, PushObjectTypeEnum.COLLABORATOR.getAlias())) {
                            result.addAll(customerUserModel.getCustomerUserIdList(corpid, Collections.singletonList(customerId), 0));
                        }
                    }
                }
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
            } else {
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
            }
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 跟进记录 501
     *
     * @param corpid
     * @param subType
     * @param userEntity
     * @param entity
     * @return
     */
    private List<String> getCustomerCommunicateUserIdList(String corpid, Integer subType, UserEntity userEntity, Entity entity) {
        String pushObjectString;
        Set<String> result = new HashSet<>();
        CustomerCommunicateEntityExt customerCommunicateEntity = (CustomerCommunicateEntityExt) entity;
        CommunicatePushSet communicatePushSet = new CommunicatePushSet();
        PushSetEntity pushSetEntity = communicatePushSet.getPushSet(corpid, subType, pushSetModel);
        JSONObject dataObject = JsonHelperUtil.getJSONObject(customerCommunicateEntity.getData());
        Long customerId = dataObject.getLong(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr());

        if (Objects.equals(pushSetEntity.getEnable(), 1)) {
            pushObjectString = pushSetEntity.getPushObject();
            JSONObject pushObject = JsonHelperUtil.parseObject(pushObjectString);
            String typeString = pushObject.getString("type");
            if (customerId != null && customerId > 0) {
                JSONArray typeJsonArray = JsonHelperUtil.parseArray(typeString);
                for (Object object : typeJsonArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    Integer enable = jsonObject.getInteger("enable");
                    if (Objects.equals(enable, 1)) {
                        String alias = jsonObject.getString("alias");
                        if (Objects.equals(alias, PushObjectTypeEnum.MAINUSER.getAlias())) {
                            result.addAll(customerUserModel.getCustomerUserIdList(corpid, Collections.singletonList(customerId), 1));
                        }
                        if (Objects.equals(alias, PushObjectTypeEnum.COLLABORATOR.getAlias())) {
                            result.addAll(customerUserModel.getCustomerUserIdList(corpid, Collections.singletonList(customerId), 0));
                        }
                    }
                }
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
            } else {
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
            }
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 访客计划 601
     *
     * @param corpid
     * @param subType
     * @param userEntity
     * @param entity
     * @return
     */
    private List<String> getCommunicatePlanUserIdList(String corpid, Integer subType, UserEntity userEntity, Entity entity) {
        //访客计划目前不做处理，且需要特殊处理，不在这里处理 ,在新建的时候读取访客计划新建消息，并用pushService中的getPushUserIdList方法获取设置的推送角色人员 @date 2018/8/6 9:25  @author 魏荣杰
        return new ArrayList<>();
    }

    /**
     * 签到
     *
     * @param corpid
     * @param subType
     * @param userEntity
     * @param entity
     * @return
     */
    private List<String> getSignInUserIdList(String corpid, Integer subType, UserEntity userEntity, Entity entity) {
        String pushObjectString;
        Set<String> result = new HashSet<>();
        SignInEntity signInEntity = (SignInEntity) entity;
        SignInPushSet signInPushSet = new SignInPushSet();
        PushSetEntity pushSetEntity = signInPushSet.getPushSet(corpid, subType, pushSetModel);

        Long customerId = signInEntity.getCustomerId();
        if (Objects.equals(pushSetEntity.getEnable(), 1)) {
            pushObjectString = pushSetEntity.getPushObject();
            if (Objects.nonNull(customerId)) {
                JSONObject pushObject = JsonHelperUtil.parseObject(pushObjectString);
                String typeString = pushObject.getString("type");
                JSONArray typeJsonArray = JsonHelperUtil.parseArray(typeString);
                for (Object object : typeJsonArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    Integer enable = jsonObject.getInteger("enable");
                    if (Objects.equals(enable, 1)) {
                        String alias = jsonObject.getString("alias");
                        if (Objects.equals(alias, PushObjectTypeEnum.MAINUSER.getAlias())) {
                            result.addAll(customerUserModel.getCustomerUserIdList(corpid, Collections.singletonList(customerId), 1));
                        }
                        if (Objects.equals(alias, PushObjectTypeEnum.COLLABORATOR.getAlias())) {
                            result.addAll(customerUserModel.getCustomerUserIdList(corpid, Collections.singletonList(customerId), 0));
                        }
                    }
                }
            }
            return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 工作报告
     *
     * @param corpid
     * @param subType
     * @param userEntity
     * @param entity
     * @return
     */
    private List<String> getWorkReportUserIdList(String corpid, Integer subType, UserEntity userEntity, Entity entity) {
        String pushObjectString;
        Set<String> result = new HashSet<>();
        //工作报告模块    工作报告设置和工作报告消息推送有重叠 特殊处理  默认推送给抄送人员，并不在设置页回显@author 魏荣杰  @date 2018/8/16 19:58
        WorkReportEntityExt workReportEntity = (WorkReportEntityExt) entity;
        WorkReportPushSet workReportPushSet = new WorkReportPushSet();
        PushSetEntity pushSetEntity = workReportPushSet.getPushSet(corpid, subType, pushSetModel);
        if (Objects.isNull(userEntity)) {
            return new ArrayList<>();
        }

        if (Objects.equals(pushSetEntity.getEnable(), 1)) {
            // 批阅人推送
            Integer type = workReportEntity.getData().getInteger(WorkReportFieldEnum.TYPE.getAttr());
            List<IdNamePropertyPojo> approvedPeopleList = getApprovedPeopleList(userEntity, type);
            List<String> approvedPeopleUserIds = getPushUserIdListFromApprovedPeople(userEntity, approvedPeopleList);
            result.addAll(approvedPeopleUserIds);
            pushObjectString = pushSetEntity.getPushObject();

            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("reportId", workReportEntity.getId());
            param.put("del", 0);
            List<WorkReportCcEntity> list = workReportCcModel.findEntitys(param);
            Set<String> userIds = new HashSet<>();
            for (WorkReportCcEntity ccEntity : list) {
                userIds.add(ccEntity.getUserId());
            }
            result.addAll(userIds);
            return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 根据批阅人获取UserId列表
     *
     * @param userEntity
     * @param approvedPeopleList
     * @return
     */
    public List<String> getPushUserIdListFromApprovedPeople(UserEntity userEntity, List<IdNamePropertyPojo> approvedPeopleList) {
        if (CollectionsUtil.isEmpty(approvedPeopleList) || Objects.isNull(userEntity)) {
            return new ArrayList<>();
        }
        Set<String> userIdSet = new HashSet<>();
        List<Integer> roleIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> depIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<String> userIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Integer> managerLevelList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        try {
            for (int i = 0; i < approvedPeopleList.size(); i++) {
                IdNamePropertyPojo idNamePropertyPojo = approvedPeopleList.get(i);
                String property = idNamePropertyPojo.getProperty();
                String id = idNamePropertyPojo.getId();
                if (Objects.equals(property, BasicConstant.ROLE)) {
                    roleIdList.add(Integer.valueOf(id));
                } else if (Objects.equals(property, BasicConstant.DYNAMICMANAGER)) {
                    managerLevelList.add(Integer.valueOf(id));
                } else if (Objects.equals(property, BasicConstant.USER)) {
                    userIdList.add(id);
                } else if (Objects.equals(property, BasicConstant.DEPT)) {
                    depIdList.add(Long.decode(id));
                }
            }
        } catch (Exception e) {
            log.warn("获取批阅人消息推送列表时 解析失败");
        }

        if (roleIdList != null && roleIdList.size() > 0) {
            List<String> roleUserIds = userModel.getUserIdsByRoles(userEntity.getCorpid(), roleIdList);
            userIdSet.addAll(roleUserIds);
        }
        if (depIdList.size() > 0) {
            List<String> depUserIds = userModel.getDepUserIdList(userEntity.getCorpid(), depIdList);
            userIdSet.addAll(depUserIds);
        }
        //上级主管
        if (userEntity != null) {
            if (managerLevelList != null && managerLevelList.size() > 0) {
                // 获取公司的所有
                List<String> depManagerIdList = getWorkReportDepManagerIdList(userEntity, managerLevelList, departmentModel, userDepartmentModel);
                userIdSet.addAll(depManagerIdList);
            }
        }
        if (userIdList != null) {
            userIdSet.addAll(userIdList);
        }
        return new ArrayList<>(userIdSet);
    }

    private List<IdNamePropertyPojo> getApprovedPeopleList(UserEntity userEntity, Integer type) {
        if (Objects.isNull(userEntity)) {
            return new ArrayList<>();
        }
        WorkReportSetEntity workReportSetEntity = workReportSetModel.getByType(type, userEntity.getCorpid());
        List<Long> userDeps = JSONArray.parseArray(userEntity.getDepartment(), Long.class);
        JSONArray jsonArray = null;
        if (workReportSetEntity != null) {
            jsonArray = workReportSetEntity.getCcUser();
        }
        JSONArray approvedPeople = new JSONArray();
        if (Objects.nonNull(jsonArray)) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                JSONArray effectiveDepsArray = Objects.isNull(jsonObject.getJSONArray(BasicConstant.EFFECTIVE_DEPS)) ? new JSONArray() : jsonObject.getJSONArray(BasicConstant.EFFECTIVE_DEPS);
                List<Long> depList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                List<IdNamePropertyPojo> depIdNameProperty = JSONArray.parseArray(effectiveDepsArray.toJSONString(), IdNamePropertyPojo.class);
                if (Objects.nonNull(depIdNameProperty) && depIdNameProperty.size() != 0) {
                    for (IdNamePropertyPojo item : depIdNameProperty) {
                        depList.add(Long.valueOf(item.getId()));
                    }
                }
                // 30946 【成功部】工作报告自动推送给所有的主管
                Boolean flag = true;
                for (Long depId : userDeps) {
                    if (depList.contains(depId)) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    continue;
                }
                // 抄送部门为空或全公司
                if (depList.isEmpty() || depList.contains(1L)) {
                    JSONArray userJson = jsonObject.getJSONArray(BasicConstant.APPROVED_PEOPLE);
                    approvedPeople.addAll(userJson);
                } else {
                    depList.retainAll(userDeps);
                    if (depList.size() >= 1) {
                        JSONArray userJson = jsonObject.getJSONArray(BasicConstant.APPROVED_PEOPLE);
                        approvedPeople.addAll(userJson);
                    }
                }
            }
        }
        List<IdNamePropertyPojo> defaultList = new ArrayList<>();
        for (int i = 0; i < approvedPeople.size(); i++) {
            JSONObject approvedPeopleJSONObject = approvedPeople.getJSONObject(i);
            IdNamePropertyPojo optionalRangeEntity = new IdNamePropertyPojo();
            optionalRangeEntity.setProperty(approvedPeopleJSONObject.getString(BasicConstant.PROPERTY));
            optionalRangeEntity.setId(approvedPeopleJSONObject.getString(BasicConstant.ID));
            optionalRangeEntity.setName(approvedPeopleJSONObject.getString(BasicConstant.NAME));
            defaultList.add(optionalRangeEntity);
        }
        return defaultList;
    }

    private List<String> getWorkReportDepManagerIdList(UserEntity userEntity, List<Integer> managerLevelList,
                                                       DepartmentModel departmentModel, UserDepartmentModel userDepartmentModel) {
        Integer maxLevel = 0;
        if (managerLevelList.size() > 0) {
            //获取最大值的部门等级 部门等级解释：假设a的所在的部门层级是 技术部-后端部-java部 ，那么a的一级部门就是 java部，2级部门就是后端部,3级部门就是技术部
            maxLevel = managerLevelList.stream().max(Comparator.comparing(Long::valueOf)).get();
        }

        List<DepartmentEntity> allDepList = new ArrayList<>();
        try {
            allDepList = departmentModel.findAllDepartment(userEntity.getCorpid(), false);
        } catch (Exception e) {
            log.error("CrmMessageSetServiceImpl.getWorkReportDepManagerIdList", e);
        }
        Map<Long, DepartmentEntity> allDepMap = new HashMap<>();
        for (DepartmentEntity dep : allDepList) {
            allDepMap.put(dep.getId(), dep);
        }
        //user所在部门
        List<Long> userInDepIds = JSONObject.parseArray(userEntity.getDepartment(), Long.class);
        if (userInDepIds == null) {
            userInDepIds = new ArrayList<>();
        }
        String userId = userEntity.getUserId();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("userIdIn", Arrays.asList(userId));
        param.put("corpid", userEntity.getCorpid());
        param.put("del", 0);
        List<UserDepartmentEntity> userDepartmentList = userDepartmentModel.findEntitys(param);

        Set<DepartmentEntity> managerDep = new HashSet<>();
        //user是否是部门主管
        if (userInDepIds.size() > 0) {
            for (Long deptId : userInDepIds) {
                // 当前员工所在的部门
                DepartmentEntity departmentEntity = allDepMap.get(deptId);
                if (Objects.isNull(departmentEntity)) {
                    continue;
                }
                //判断当前user是否是dept部门主管
                Boolean flag = false;
                for (UserDepartmentEntity userDepartmentEntity : userDepartmentList) {
                    if (Objects.equals(userDepartmentEntity.getUserId(), userId) && Objects.equals(userDepartmentEntity.getDepartmentId(), departmentEntity.getId()) && Objects.equals(userDepartmentEntity.getIsLeader(), 1)) {
                        flag = true;
                    }
                }

                //key为部门id value表示是否是主管
                //找不到key对应的value、或key对应的value不是true表示非主管
                Set<DepartmentEntity> pointDepSet = null;
                //获取层级managerLevelList对应的所有部门
                if (!flag) {
                    for (Integer i = 1; i < maxLevel + 1; i++) {
                        // 当前user非主管的时候，读取一级主管时，取当前部门的主管
                        if (i == 1) {
                            //读取所在部门,第一次时，用所在部门初始化pointDepSet
                            pointDepSet = new HashSet<>();
                            for (Long depId : userInDepIds) {
                                DepartmentEntity tempDep = allDepMap.get(depId);

                                if (tempDep != null) {
                                    pointDepSet.add(tempDep);
                                }
                            }
                            if (managerLevelList.contains(i)) {
                                managerDep.addAll(pointDepSet);
                            }
                            continue;
                        }
                        Set<DepartmentEntity> parentDepSet = new HashSet<>();
                        for (DepartmentEntity dep : pointDepSet) {
                            DepartmentEntity tempDep = allDepMap.get(dep.getParentId());
                            if (tempDep != null) {
                                parentDepSet.add(tempDep);
                            }
                        }
                        pointDepSet = parentDepSet;
                        if (managerLevelList.contains(i)) {
                            managerDep.addAll(pointDepSet);
                        }
                    }
                } else {
                    // 部门ID路由
                    List<Long> routDepIds = StringUtil.toLongList(departmentEntity.getDepIdRouter(), "|");
                    int size = routDepIds.size();

                    // 当前user为主管，推送给上一级部门的主管
                    for (Integer levelInt : managerLevelList) {
                        if (levelInt > 0) {
                            levelInt++;
                        }
                        // 顶级主管
                        if (levelInt > size || levelInt == -1) {
                            continue;
                        } else if (levelInt == 0) {
                            // 不选择动态负责人
                            continue;
                        } else {
                            // 级别的主管
                            Long depId = routDepIds.get(size - levelInt);
                            DepartmentEntity tempDep = allDepMap.get(depId);
                            managerDep.add(tempDep);
                        }
                    }
                }
            }
        }

        if (managerDep.isEmpty()) {
            return new ArrayList<>();
        }

        //获取完managerLevelList对应的所有部门
        List<Long> managerDepIdList = new ArrayList<>();
        for (DepartmentEntity dep : managerDep) {
            if (Objects.isNull(dep)) {
                continue;
            }
            managerDepIdList.add(dep.getId());
        }
        List<UserDepartmentEntity> userDepList = new ArrayList<>();
        if (managerDepIdList.size() > 0) {
            Map<String, Object> params = new HashMap<>();
            params.put("corpid", userEntity.getCorpid());
            params.put("departmentIdIn", managerDepIdList);
            params.put("isLeader", 1);
            params.put("del", 0);
            userDepList = userDepartmentModel.findEntitys(params);
        }

        List<String> depManagerIdList = new ArrayList<>();
        for (UserDepartmentEntity userDep : userDepList) {
            depManagerIdList.add(userDep.getUserId());
        }
        depManagerIdList.remove(userEntity.getUserId());

        return depManagerIdList;
    }

    /**
     * 报价单
     *
     * @param corpid
     * @param subType
     * @param userEntity
     * @param entity
     * @return
     */
    private List<String> getQuotationUserIdList(String corpid, Integer subType, UserEntity userEntity, Entity entity) {
        String pushObjectString;
        Set<String> result = new HashSet<>();
        QuotationEntityExt quotationEntityExt = (QuotationEntityExt) entity;
        QuotationPushSet quotationPushSet = new QuotationPushSet();
        PushSetEntity pushSetEntity = quotationPushSet.getPushSet(corpid, subType, pushSetModel);
        Long quotationId = quotationEntityExt.getId();

        if (Objects.equals(pushSetEntity.getEnable(), 1)) {
            pushObjectString = pushSetEntity.getPushObject();
            JSONObject pushObject = JsonHelperUtil.parseObject(pushObjectString);
            String typeString = pushObject.getString("type");
            if (quotationId != null && quotationId > 0) {
                JSONArray typeJsonArray = JsonHelperUtil.parseArray(typeString);
                for (Object object : typeJsonArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    Integer enable = jsonObject.getInteger("enable");
                    if (Objects.equals(enable, 1)) {
                        String alias = jsonObject.getString("alias");
                        if (Objects.equals(alias, PushObjectTypeEnum.MAINUSER.getAlias())) {
                            result.addAll(quotationUserModel.getQuotationUserIdList(corpid, quotationEntityExt.getId(), 1));
                        }
                        if (Objects.equals(alias, PushObjectTypeEnum.COLLABORATOR.getAlias())) {
                            result.addAll(quotationUserModel.getQuotationUserIdList(corpid, quotationEntityExt.getId(), 0));
                        }
                        if (Objects.equals(alias, PushObjectTypeEnum.QUOTATION_PERSON.getAlias())) {
                            JSONObject quotationDataObject = JsonHelperUtil.getJSONObject(quotationEntityExt.getData());
                            result.add(quotationDataObject.getString(QuotationEnum.QUOTATION_PERSON.getAttr()));
                        }
                    }
                }
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
            } else {
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
            }
        } else {
            return new ArrayList<>();
        }
    }

/*    if (Objects.equals(PushTypeEnum.CUSTOMER_PUSH.getCode(), type)) {
        userIds = getCustomerManageMentUserIdList(corpid, subType, userEntity, entity);
    } else if (Objects.equals(PushTypeEnum.CUSTOMER_REMIND.getCode(), type)) {
        userIds = getCustomerRemindUserIdList(corpid, subType, userEntity, entity);
    } else if (Objects.equals(PushTypeEnum.CONTACT_PUSH.getCode(), type)) {
        userIds = getContactUserIdList(corpid, subType, userEntity, entity);
    } else if (Objects.equals(PushTypeEnum.OPPORTUNITY_PUSH.getCode(), type)) {
        userIds = getSalesOpportunityUserIdList(corpid, subType, userEntity, entity);
    } else if (Objects.equals(PushTypeEnum.COMMUNICATE_PLAN_PUSH.getCode(), type)) {
        userIds = getCommunicatePlanUserIdList(corpid, subType, userEntity, entity);
    } else if (Objects.equals(PushTypeEnum.COMMUNICATE_PUSH.getCode(), type)) {
        userIds = getCustomerCommunicateUserIdList(corpid, subType, userEntity, entity);
    } else if (Objects.equals(PushTypeEnum.CONTRACT_PUSH.getCode(), type)) {
        userIds = getContractUserIdList(corpid, subType, userEntity, entity);
    } else if (Objects.equals(PushTypeEnum.SIGN_IN_ADD_PUSH.getCode(), type)) {
        userIds = getsignInUserIdList(corpid, subType, userEntity, entity);
    } else if (Objects.equals(PushTypeEnum.WORK_REPORT_PUSH.getCode(), type)) {
        userIds = getWorkReportUserIdList(corpid, subType, userEntity, entity);
    } else if (Objects.equals(PushTypeEnum.QUOTATION_PUSH.getCode(), type)) {
        userIds = getQuotationUserIdList(corpid, subType, userEntity, entity);
    }*/
}
